import { Injectable } from '@angular/core';
import {NzMessageService, UploadXHRArgs} from 'ng-zorro-antd';
import {HttpRequest, HttpResponse, HttpEventType, HttpEvent, HttpClient, HttpHeaders} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class UploadApiService {

  constructor(private http: HttpClient,private msg: NzMessageService) { }

  public upload(item: UploadXHRArgs,callback: any) {
    const id = this.msg.loading('正在上传...', { nzDuration: 0 }).messageId;
    // 构建一个 FormData 对象，用于存储文件或其他参数
    const formData = new FormData();
    // tslint:disable-next-line:no-any
    formData.append('file', item.file as any);
    console.log(item);
    const req = new HttpRequest('POST', item.action, formData, {
      reportProgress : true,
      withCredentials: true,
      headers: new HttpHeaders()
    });

    // 始终返回一个 `Subscription` 对象，nz-upload 会在适当时机自动取消订阅
    return this.http.request(req).subscribe((event: HttpEvent<{}>) => {
      if (event.type === HttpEventType.UploadProgress) {
        if (event.total > 0) {
          // tslint:disable-next-line:no-any
          (event as any).percent = event.loaded / event.total * 100;
        }
        // 处理上传进度条，必须指定 `percent` 属性来表示进度
        item.onProgress(event, item.file);
      } else if (event instanceof HttpResponse) {
        // 处理成功
        callback(event.body);
        item.onSuccess(event.body, item.file, event);
        this.msg.remove(id);
      }
    }, (err) => {
      // 处理失败
      item.onError(err, item.file);
    });
  }
}
